﻿$(document).ready(function () {
    $("input:submit").button();

    /// Slide down the input options for our textarea (#chars left & submit button)
    $('textarea#Yelp').focusin(function () {
        $("#YelpSubmit").attr("disabled", "disabled");
        $("div#YelpInputOptions").slideDown("slow");
    });

    /// Check how many characters we have left
    $("textarea#Yelp").toObservable("keyup").Select(function (event) { return $(event.target).val(); }).Subscribe(function (value) {

        var sizeleft = 141 - value.length;

        $("#CharactersLeft").html(sizeleft);

        if (sizeleft <= 0) {
            $('#CharactersLeft').addClass('overflow');
        } else {
            $('#CharactersLeft').removeClass('overflow');
        }

        if (sizeleft < 0 || sizeleft == 141) {
            $("#YelpSubmit").attr("disabled", "disabled");
        } else {
            $("#YelpSubmit").removeAttr("disabled");
        }
    });

    /// Username autocomplete when sending a Yelp
    $("textarea#Yelp").toObservable("keyup").Select(function (event) { return $("textarea#Yelp").val(); }).Throttle(60).Subscribe(function (value) {

        var last = value.split(" ").pop();

        if (last.substring(0, 1) == "@" && last.length > 1) {

            var filter = last.substring(1, (last.length));

            $('#YelpUserSuggestions').load('/Users/' + filter, function (response, status, xhr) {
                // Our website returns 405 when there a no users found that match the filter
                if (xhr.status == "405") {
                    $("#YelpUserSuggestions").empty();
                    $('#YelpUserSuggestions').hide();
                } else {
                    $('#YelpUserSuggestions').slideDown("slow");
                }
            });

        } else {
            $("#YelpUserSuggestions").empty();
            $('#YelpUserSuggestions').hide();
        }
    });

    // Click action UserSuggestions
    $(".UserSuggestion").live("click", function (event) {

        var current = $("textarea#Yelp").val();

        var lastlength = current.split(" ").pop().length;
        var yelp = current.substring(0, current.length - lastlength);

        var username = $(this).find(".Username").text();

        $("textarea#Yelp").focus();

        $("textarea#Yelp").html(yelp + "@" + username + " ");

        $("#YelpUserSuggestions").empty();
        $('#YelpUserSuggestions').hide();


    });


});

function YelpSuccess() {

    $("textarea#Yelp").val("");
    $("#CharactersLeft").html(141);
    $("#CharactersLeft").removeClass('overflow');
    $("#YelpSubmit").attr("disabled", "disabled");

}

